<?php
namespace App\Admin\Controllers\Basics;

use App\Admin\Ajax\Basics\AmazonAccountAdsAjax;
use App\Models\Basics\AmazonAccount;
use App\Models\Basics\AmazonAccountAds;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Admin as RAdmin;
use Encore\Admin\Form;
use Encore\Admin\Grid;

class AmazonAccountAdsController extends AdminController{

    protected $title = '亚马逊广告账号';

    protected function grid()
    {
        RAdmin::script($this->_script());
        $grid = new Grid(new AmazonAccountAds());
        $grid->model()->orderBy('id','DESC');

        $grid->column('id','ID')->style('width: 5%')->sortable();
        $grid->column('amazon_account.account','广告账号')->help('可模糊查询');
        $grid->column('amazon_account.aws_region','广告区域')->display(function ($value){
            return AmazonAccount::$_awsRegion[$value];
        })->filter(AmazonAccount::$_awsRegion);
        $grid->column('amazon_account.merchant','卖家编号')->help('可模糊查询');
        $grid->column('auth_status','广告授权状态')->using(AmazonAccountAds::$_authStatus)->filter(AmazonAccountAds::$_authStatus)->label([1 => 'success', 0 => 'default']);
        if(Admin::user()->can('account.edit')){
            $grid->column('auth_at','广告授权时间')->display(function ($v){
                if($this->api == 1){
                    if($v){
                        $i = strtotime($v) - strtotime('-1 year');
                        if($i <= 0){
                            $str = "<span class='label-danger'>".$v."(已到期)</span>";
                        }elseif($i < AmazonAccountAds::AUTH_AT_EXPIRED){
                            $str = "<span class='label-warning'>".$v."(即将到期)</span>";
                        }else{
                            $str = "<span class='label-default'>".$v."(已授权)</span>";;
                        }
                        return $str;
                    }else{
                        return '异常';
                    }
                }else{
                    return '';
                }
            });
            $grid->column('api','API')->bool()->filter(AmazonAccountAds::$_api);
        }
        if(Admin::user()->can('account.edit')){
            $grid->column('操作')->view('basics.amazon-account-ads.action');
        }else{
            $grid->disableCreateButton();
        }
        $grid->disableActions();
        $grid->disableRowSelector();
        $grid->disableExport();
        $grid->filter(function(Grid\Filter $filter){
            $filter->column(1/3, function ($filter) {
                $filter->equal('account_id','账号')->select(AmazonAccount::options());
            });
        });

        return $grid;
    }

    protected function _script()
    {
        $token = csrf_token();

        return <<<EOT
//广告授权
$('.grid-check-oauth-ads').unbind('click').click(function(e) {
    e.preventDefault();
    var id = $(this).data('id');
    $.ajax({
        method: 'post',
        url: '/xqc/basics/amazon-account-ads-ajax',
        data: {
            _token: "{$token}",
            param:id,
            action:'doOauth'
        },
        success: function (data) {
            if (typeof data === 'object') {
                if (data.status) {
                    swal({
                        title: "跳转亚马逊后台授权广告？",
                        text: "点击前往将跳转亚马逊店铺后台进行广告授权，请确保在常用环境操作，避免关联",
                        type: "warning",
                        showCancelButton: true,
                        confirmButtonColor: "#DD6B55",
                        confirmButtonText: "前往",
                        cancelButtonText: "取消",
                        reverseButtons: true,
                    }).then(function(result) {
                        if (result.value) {
                           window.open(data.oauth_url);
                        }
                    });
                } else {
                    swal(data.message, '', 'error');
                }
            }
        }
    });
});
EOT;
    }

    public function ajax(){
        $action = request('action');
        $param = request('param');
        $ajax = new AmazonAccountAdsAjax();
        return $param ? call_user_func([$ajax,$action],$param) : call_user_func([$ajax,$action]);
    }

    public function form()
    {
        $form = new Form(new AmazonAccountAds());

        $form->hidden('id');
        //select联动----------
        if ($form->isEditing()) {
            $form->select('account_id', '广告账号')
                ->options(AmazonAccount::options())
                ->required()->readonly();
        }else{
            $form->select('account_id', '广告账号')
                ->options(AmazonAccount::options())
                ->required();
        }
        //--------------
        $form->radio('api','API')->options(AmazonAccount::$_api)->default(0);
        //API字段------
        $form->display('refresh_token','Token')->help('亚马逊API字段-授权后生成');
        $form->display('auth_at', '广告授权时间')->help('授权后更新');
        $form->hidden('auth_status', '广告授权状态')->default(0);
        //--------
        $form->hidden('created_at');
        $form->hidden('updated_at');

        $form->saving(function (Form $form) {

        });
        //$form->saved(function (Form $form) {
        //    if($form->model()->status == 0){
        //        ProductAmazonSku::query()
        //            ->where('account_id',$form->model()->id)
        //            ->where('status',1)
        //            ->update(['status' => 2]);
        //    }
        //});
        $form->tools(function (Form\Tools $tools) {
            $tools->disableView();
            $tools->disableDelete();
        });
        return $form;
    }
}
